package me.zhengjie.modules.forecast.rest;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.heshuo.amm.exception.CheckException;
import com.heshuo.amm.exception.DatabaseException;
import com.heshuo.amm.model.PLMessage;
import com.heshuo.amm.model.PLMessageAttach;
import com.heshuo.amm.model.User;
import com.heshuo.amm.service.IPLMessageReleaseService;
import com.heshuo.amm.service.ISystemConfigService;
import com.heshuo.amm.service.PLMessageReleaseServiceImpl;
import com.heshuo.amm.util.FileUtils;

import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDTO;
import me.zhengjie.utils.SecurityUtils;

@RestController
@RequestMapping("api")
public class PLMessageController {

	@Autowired
	ISystemConfigService systemConfigService;
    @Autowired
    private UserService userService;

	private IPLMessageReleaseService iPLMessageReleaseService = new PLMessageReleaseServiceImpl();

	@GetMapping(value = "/plmessage/searchPLMessage")
	public ResponseEntity searchPLMessage(@RequestParam(value="start",required=false)Date start,@RequestParam(value="end",required=false)Date end) throws DatabaseException {
		List<PLMessage> list = iPLMessageReleaseService.searchPLMessage(start, end, null, null, null, null, null, null);
		UserDTO userDto = userService.findById(SecurityUtils.getUserId());
		List<PLMessage> listByUser = new ArrayList<PLMessage>();
		for (PLMessage pm : list) {
			if(null==userDto.getDept().getAirportCode()||userDto.getDept().getAirportCode().equalsIgnoreCase(pm.getCccc())){
					listByUser.add(pm);
			}
			if (pm.getAttaches().size() > 0) {
				// pm.setFilename(pm.getAttaches());
				pm.setFilename(pm.getAttaches().iterator().next().getName());
			}
			pm.setAttaches(null);
		}
		Map res = new HashMap();
		res.put("totalElements", listByUser.size());
		res.put("content", listByUser);
		return new ResponseEntity(res, HttpStatus.OK);
	}

	@PostMapping(value="/plmessage/getFile")
	public void getFile(@RequestBody String id,HttpServletRequest request,
            HttpServletResponse response) throws UnsupportedEncodingException{
		String folder=System.getProperty("java.io.tmpdir");
		PLMessage plMessage = null;
		try {
			plMessage = iPLMessageReleaseService.searchPLMessage(id);
			Set<PLMessageAttach> atts = plMessage.getAttaches();
			if(atts.iterator().hasNext()){
				PLMessageAttach att= atts.iterator().next();
				response.setHeader("content-type", "application/octet-stream");
	            response.setContentType("application/octet-stream");
	            // 下载文件能正常显示中文
	            response.setHeader("Content-Disposition", "attachment;filename=" + new String(att.getName().getBytes("gb2312"),"iso-8859-1"));

				 OutputStream os=null;
				try {
					os = response.getOutputStream();
					 os.write(FileUtils.getContent(new File(att.getPath())));
					 os.flush();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
						try {
							if(os!=null)os.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
				}
			}else{
				
			}
		} catch (DatabaseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
	}
	@GetMapping(value = "/plmessage/lastPLMessage")
	public ResponseEntity lastPLMessage(@RequestParam(value="airport",required=false)String airport,@RequestParam(value="type",required=false)String type) throws DatabaseException {
		List<PLMessage> list = iPLMessageReleaseService.searchPLMessage(null, null, null, null, null, null, null, null);
		for (PLMessage pm : list) {
			if (pm.getAttaches().size() > 0) {
				// pm.setFilename(pm.getAttaches());
			}
			pm.setAttaches(null);
		}
		Map res = new HashMap();
		res.put("totalElements", list.size());
		res.put("content", list);
		return new ResponseEntity(res, HttpStatus.OK);
	}

	@PostMapping(value = "/plmessage/savePLMessage")
	public ResponseEntity savePLMessage(@RequestParam(value="uploadFile", required = false) MultipartFile uploadFile, PLMessage plmessage)
			throws DatabaseException, CheckException, IOException {
		if(uploadFile!=null){
			Set<PLMessageAttach> set = new HashSet<PLMessageAttach>();
			PLMessageAttach pla = new PLMessageAttach();
			pla.setName(uploadFile.getOriginalFilename());
			pla.setSize("" + uploadFile.getSize());
			pla.setContent(uploadFile.getBytes());
			File tempFile = FileUtils.createTempFile();
			uploadFile.transferTo(tempFile);
			pla.setPath(tempFile.getAbsolutePath());
			
//			File f = uploadFile.getResource().getFile();
			set.add(pla);
			plmessage.setAttaches(set);
		}
		UserDTO userDto = userService.findById(SecurityUtils.getUserId());
		
		plmessage.setForecaster(userDto.getDept().getName()+"/"+userDto.getUsername());
		iPLMessageReleaseService.savePLMessage(plmessage);
		return new ResponseEntity(true, HttpStatus.OK);
	}
}
